package org.wutopia.leocloud.domain.account.resource;

import jakarta.validation.Valid;
import jakarta.ws.rs.core.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
//import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.wutopia.leocloud.domain.account.application.AccountApplicationService;
import org.wutopia.leocloud.domain.account.domain.validation.AuthenticatedAccount;
import org.wutopia.leocloud.domain.account.domain.validation.NotConflictAccount;
import org.wutopia.leocloud.domain.account.domain.validation.UniqueAccount;
import org.wutopia.leocloud.library.common.domain.account.Account;
import org.wutopia.leocloud.library.common.infrastructure.common.CommonResponse;


/**
 * 用户资源
 * <p>
 * 对客户端以Restful形式暴露资源，提供对用户资源{@link Account}的管理入口
 **/

@RequestMapping("/accounts")
@RestController
@CacheConfig(cacheNames = "resource.account")
public class AccountResource {
    private static final Logger log = LoggerFactory.getLogger(AccountResource.class);
    @Autowired
    private AccountApplicationService service;

    /**
     * 根据用户名称获取用户详情
     */
    @GetMapping("/{username}")
    @Cacheable(key = "#p0")
    public Account getUser(@PathVariable("username") String username) {
        log.info("username: {}", username);
        return service.findAccountByUsername(username);
    }

    /**
     * 创建新的用户
     */
    @PostMapping("/")
    @CacheEvict(key = "#user.username")
    public Response createUser(@Valid @UniqueAccount Account user) {
        return CommonResponse.op(() -> service.createAccount(user));
    }

    /**
     * 更新用户信息
     */
    @PutMapping("/")
    @CacheEvict(key = "#user.username")
    public Response updateUser(@Valid @AuthenticatedAccount @NotConflictAccount Account user) {
        return CommonResponse.op(() -> service.updateAccount(user));
    }
}
